package com.javabasic.tool;

import com.javabasic.tool.model.Car;
import com.javabasic.tool.model.Person;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author xiongmin
 * @Description TODO 将Java类转化为map key为属性名 value 为对应的属性值
 * @Date 2019/10/25 11:41
 * @Version 1.0
 **/
public class BeanToMapUtils {

    public static void main(String[] args) throws Exception{

        try {
            String str = "Invalid Range";
            long value = Long.parseLong(str);
            System.out.println("value = " + value);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            System.out.println("该返回值是一个字符串");
        }

        Car car = new Car();
        car.setId("00000");
        car.setColor("black");
        car.setModel("bmw x5");
        car.setVolume("3.0L");
        car.setYear(2018);

        Person person = new Person();
        person.setAge(22);
        person.setName("hans");
        car.setPerson(person);

        if (car.getPerson() instanceof Person) {
            System.out.println("is Person");
        }
        if (car.getVolume() instanceof String) {
            System.out.println("is String");
        }
        if (car.getYear() instanceof Number) {
            System.out.println("is Number");
        }

        System.out.println(objectToMap(car));

        int x = 10;
        HashMap<String, Object> map = new HashMap<>();
        map.put("x",x);
        if (map.get("x") instanceof Integer) {
            System.out.println("is Number");
        } else {
            System.out.println("is not Number");
        }

        final Integer integer = new Integer(x);
        System.out.println(integer.toString());
    }

    /**
     * 将Object对象里面的属性和值转化成Map对象
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }
}
